package cn.ticsmyc.tools.framework.ioc.context;

import cn.ticsmyc.tools.framework.ioc.entity.BeanDefinition;
import cn.ticsmyc.tools.framework.ioc.factory.AbstractBeanFactory;
import cn.ticsmyc.tools.framework.ioc.factory.AutowiredCapableBeanFactory;
import cn.ticsmyc.tools.framework.ioc.io.ResourceLoader;
import cn.ticsmyc.tools.framework.ioc.reader.XmlBeanDefinitionReader;

import java.util.Map;

/**
 * @author Ticsmyc
 * @date 2021-05-24 21:12
 */
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {

    private String xmlFilePath;

    public ClassPathXmlApplicationContext(String xmlFilePath) {
        super();
        this.xmlFilePath = xmlFilePath;
        refresh();
    }

    private void refresh() {
        synchronized (this) {
            //解析xml配置，封装成beanDefinition
            AbstractBeanFactory beanFactory = obtainBeanFactory();
            //实例化所有单例bean
            prepareBeanFactory(beanFactory);
            this.beanFactory = beanFactory;
        }
    }

    private AbstractBeanFactory obtainBeanFactory() {
        XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(new ResourceLoader());
        try {
            xmlBeanDefinitionReader.loadBeanDefinition(xmlFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, BeanDefinition> registry = xmlBeanDefinitionReader.getRegistry();

        AutowiredCapableBeanFactory beanFactory = new AutowiredCapableBeanFactory();
        registry.entrySet().forEach(entry -> {
            try {
                beanFactory.registerBeanDefinition(entry.getKey(), entry.getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return beanFactory;
    }

    private void prepareBeanFactory(AbstractBeanFactory beanFactory) {
        try {
            //提前实例化所有单例的bean
            beanFactory.populateBeans();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
